<?php
// 公众号模板
// https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html

namespace JyWxThird\Init\Mp;

use JyWxThird\Kernel\Http;

trait Template
{
  /**
   * 设置所属行业
   *
   * @param int $industry_id1 行业1
   * @param int $industry_id2 行业2
   * @return bool
   */
  public function tpSetIndustry($industry_id1, $industry_id2)
  {
    $param = [
      'industry_id1' => $industry_id1,
      'industry_id2' => $industry_id2,
    ];
    $url   = $this->domainUrl . "/cgi-bin/template/api_set_industry?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpPost($url, $param));
  }
  
  /**
   * 获取设置的行业信息
   *
   * @return bool
   */
  public function tpGetIndustry()
  {
    $url = $this->domainUrl . "/cgi-bin/template/get_industry?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpGet($url), 'primary_industry');
  }
  
  /**
   * 添加模板
   *
   * @param string $template_id_short 模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式
   * @return bool
   */
  public function tpAdd($template_id_short)
  {
    $param = [
      'template_id_short' => $template_id_short,
    ];
    $url   = $this->domainUrl . "/cgi-bin/template/api_add_template?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpPostRaw($url, json_encode($param, JSON_UNESCAPED_UNICODE)), 'template_id');
  }
  
  /**
   * 获取模板列表
   *
   * @return bool
   */
  public function tpGetList()
  {
    $url = $this->domainUrl . "/cgi-bin/template/get_all_private_template?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpGet($url), 'template_list');
  }
  
  /**
   * 删除模板
   *
   * @param string $template_id 公众帐号下模板消息ID
   * @return bool
   */
  public function tpDel($template_id)
  {
    $param = [
      'template_id' => $template_id,
    ];
    $url   = $this->domainUrl . "/cgi-bin/template/del_private_template?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpPostRaw($url, json_encode($param, JSON_UNESCAPED_UNICODE)));
  }
  
  /**
   * 发送模板消息
   *
   * @return bool
   */
  public function tpSend($param)
  {
    if (is_string($param)) {
      if (!$temp = json_decode($param, true)) {
        $this->setError('你提供的JSON参数，格式有误，请检查');
        return false;
      }
      $param = $temp;
    }
    $url = $this->domainUrl . "/cgi-bin/message/template/send?access_token=" . $this->get_access_token();
    return $this->handleReturn(Http::httpPostRaw($url, json_encode($param, JSON_UNESCAPED_UNICODE)));
  }
}
